package com.yjb.tenet.boot.system.application.checker;

import cn.hutool.core.util.ObjectUtil;
import com.yjb.tenet.boot.common.constants.GlobalConstants;
import com.yjb.tenet.boot.common.enums.DataTypeEnum;
import com.yjb.tenet.boot.common.enums.RoleCodeEnum;
import com.yjb.tenet.boot.common.exception.CustomException;
import com.yjb.tenet.boot.common.exception.enums.ErrorCodeEnum;
import com.yjb.tenet.boot.system.application.service.SysRoleService;
import com.yjb.tenet.boot.system.domain.entity.SysRole;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description 
 * @author yinjinbiao
 * @create 2023/2/23 16:55
 * @version 1.0
 */
@Component
public class SysRoleChecker {

	@Resource
	public SysRoleService sysRoleService;

	/**
	 * 是否存在相同角色
	 * @param roleCode
	 */
	public void checkForExist(Long roleId, String roleCode){
		if(RoleCodeEnum.isSuperAdmin(roleCode)){
			throw new CustomException(ErrorCodeEnum.BUSINESS_FAIL.getCode(), "参数非法！");
		}

		SysRole one = sysRoleService.lambdaQuery()
				.eq(SysRole::getDeleted, GlobalConstants.NOT_DELETED)
				.eq(SysRole::getRoleCode, roleCode)
				.eq(ObjectUtil.isNotEmpty(roleId), SysRole::getId, roleId)
				.one();
		// 如果存在数据 则说明数据重复
		if(ObjectUtil.isNotNull(one)){
			throw new CustomException(ErrorCodeEnum.BUSINESS_FAIL.getCode(), "该角色已存在！");
		}
	}

	/**
	 * 是否不可更新
	 * @param roleId
	 * @return
	 */
	public SysRole checkForOperate(Long roleId){
		SysRole sysRole = sysRoleService.getById(roleId);
		if(ObjectUtil.isNull(sysRole)){
			throw new CustomException(ErrorCodeEnum.PARAM_ILLEGAL.getCode(), "角色不存在！");
		}
		if(DataTypeEnum.SYSTEM.getValue().equals(sysRole.getType())){
			throw new CustomException(ErrorCodeEnum.PERMISSION_DENY.getCode(), "内置角色无法操作！");
		}
		return sysRole;
	}
}
